package org.abettor.pushbox.map;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.abettor.pushbox.view.BoxMapThumbnailDraw;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;

/**
 * 动态产生图片的缩略图,用于本地的操作
 * 
 * @author jzh
 * 
 */
public abstract class AsyncGenerateMapThumbImage {
	private ImageCallback callback;// 回掉接口
	private final Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			callback.processImage(bitmap);
		}
	};
	protected Bitmap bitmap ;
	protected BoxMapThumbnailDraw mapThumbnailDraw;//缩略图的绘制类
	public static interface ImageCallback {
		// 处理图片
		public void processImage(Bitmap bit);
	}

	// 获得所在目录的路径
	public abstract String getThumbNailPath();
	public abstract String getMapFilePath();

	public AsyncGenerateMapThumbImage(float width,
			float height, ImageCallback callback,Context context) {
		this.callback = callback;
		this.mapThumbnailDraw = new BoxMapThumbnailDraw(context);
		this.mapThumbnailDraw.setHeight(height);
		this.mapThumbnailDraw.setWidth(width);
	}
	//产生地图缩略图
	protected Bitmap generateImage(){
		byte [] buf = null;
		try {
			buf = readFile();
		} catch (IOException e) {
		}
		if(buf==null)
			return null;
		Boxmap map = BoxmapUtil.paraArrayToMap(buf);//生成地图
		//先读取文件看存在不存在,存在的话读取已存在的图片
		String filepath = getThumbNailPath();
		Bitmap bmp = null;
		File file = new File(filepath);
		if(file.exists()){//读取存在的文件
			bmp = readBitmap(file);
		}
		if(bmp != null){
			return bmp;
		}
		mapThumbnailDraw.setMap(map);
		bmp = mapThumbnailDraw.draw();
		//在本地存一份
		generateThumbnail(bmp,filepath);
		return bmp;
	}
	//在sd卡上存一个缩略图
	protected void generateThumbnail(Bitmap bmp,String filepath){
		FileOutputStream os;
		try {
			os = new FileOutputStream(filepath);
			bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
			os.close();
		} catch (IOException e) {
		}
	}
	//从文件读取图像
	protected Bitmap readBitmap(File file){
		FileInputStream is;
		try {
			is = new FileInputStream(file);
			Bitmap bitmap = BitmapFactory.decodeStream(is);
			return bitmap;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	//读取地图文件
	protected byte [] readFile() throws IOException{
		String filepath = getMapFilePath();
		File file = new File(filepath);
		if(!file.exists()){
			return null;
		}
		InputStream in = new FileInputStream(file);
		ByteArrayOutputStream byteout = new ByteArrayOutputStream();
		int value = 0;
		while((value = in.read())!=-1){
			byteout.write(value);
		}
		return byteout.toByteArray();
	}
	/**
	 * 开始执行操作
	 */
	public void start(){
		new Thread(){
			@Override
			public void run(){
				bitmap = generateImage();
				handler.sendEmptyMessage(0);
			}
		}.start();
	}
}
